package org.zoomdev.zoom.protobuf.modules;

import io.protostuff.ByteArrayInput;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffOutput;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.serializer.Serializer;

import java.io.IOException;

/**
 * 数据量会增加50字节以上
 */
public final class CommonProtostuffSerializer implements Serializer {
    public static final Serializer SERIALIZER = new CommonProtostuffSerializer();


    public CommonProtostuffSerializer() {
    }

    @Override
    public byte[] serialize(Object data) {
        if (data == null) {
            return ISchemaProtostuffSerializer.EMPTY;
        }
        try {
            LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
            ProtostuffOutput output = new ProtostuffOutput(buffer);
            ISchema schema = IUnknownSchemaRegistry.getSchema(data.getClass());

            schema.write(output, 1, data, false);
            return output.toByteArray();
        } catch (IOException e) {
            throw new ZoomException(e);
        }

    }

    @Override
    public Object deserialize(byte[] bytes) {
        try {
            if (bytes == null || bytes.length == 0) {
                return null;
            }
            ByteArrayInput input = new ByteArrayInput(bytes, 0, bytes.length, true);
            input.readFieldNumber(null);
            int index = input.readInt32();
            ISchema schema = IUnknownSchemaRegistry.getSchema(index);
            return schema.mergeFrom(input);
        } catch (IOException e) {
            throw new ZoomException(e);
        }
    }

}
